package com.zhou.Controller;

import com.zhou.domain.Msg;
import com.zhou.server.impl.MsgServerImpl;
import com.zhou.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Slf4j
@ServerEndpoint("/chat/{name}/{hyname}")
public class WebSocket {

    @Autowired
    private MsgServerImpl msgServer;

    //@Autowired
    //private RedisTemplate<String, Object> redisTemplate;

    /*
     * 提供一个spring context上下文(解决方案)
     */
    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocket.applicationContext = applicationContext;
    }


    /**
     * 用来解决webSocket中无法注入mapper
     */
    //private static ApplicationContext applicationContext;


    /**
     * 线程安全的无序的集合
     */
    private static final CopyOnWriteArraySet<Session> SESSIONS = new CopyOnWriteArraySet<>();

    /**
     * 存储在线连接数
     */
    private static final Map<String, Session> SESSION_POOL = new HashMap<>();

    //建立连接时调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "name") String name, @PathParam(value = "hyname") String hyname) {



        try {
            SESSIONS.add(session);
            SESSION_POOL.put(name,session);
            log.info("【WebSocket消息】有新的连接，总数为：" + SESSIONS.size());
//            msg msg = new msg();
//            msg.setName(name);
//            session.getAsyncRemote().sendText(JsonUtil.serialize());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //断开连接时调用
    @OnClose
    public void onClose(Session session) {
        try {
            SESSIONS.remove(session);
            log.info("【WebSocket消息】连接断开，总数为：" + SESSIONS.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //接受消息时调用
    @OnMessage
    public void onMessage(String message,Session session) throws Exception {
        //JsonUtil.deserialize(message);
        log.info("【WebSocket消息】收到客户端消息：" + message);
        Msg deserialize = JsonUtil.deserialize(message, Msg.class);
        System.out.println(deserialize);
        if(SESSION_POOL.get(deserialize.getName())==null){
            SESSION_POOL.put(deserialize.getName(),session);
        }
        if(SESSION_POOL.get(deserialize.getHyname())!=null){
            SESSION_POOL.get(deserialize.getHyname()).getAsyncRemote().sendText(JsonUtil.serialize(deserialize));
        }
        session.getAsyncRemote().sendText(JsonUtil.serialize(deserialize));

        //msgServer.addmsg(deserialize);
        //RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
        //redisTemplate.convertAndSend("redis.msg", message);

    }

    /**
     * 此为广播消息
     *
     * @param message 消息
     */
    public void sendAllMessage(String message) {
        log.info("【WebSocket消息】广播消息：" + message);
        for (Session session : SESSIONS) {
            try {
                if (session.isOpen()) {
                    //发送消息API
                    session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 此为单点消息
     *
     * @param userId  用户编号
     * @param message 消息
     */
    public void sendOneMessage(String userId, String message) {
        Session session = SESSION_POOL.get(userId);
        if (session != null && session.isOpen()) {
            try {
                synchronized (session) {
                    log.info("【WebSocket消息】单点消息：" + message);
                    session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 此为单点消息(多人)
     *
     * @param userIds 用户编号列表
     * @param message 消息
     */
    public void sendMoreMessage(String[] userIds, String message) {
        for (String userId : userIds) {
            Session session = SESSION_POOL.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    log.info("【WebSocket消息】单点消息：" + message);
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


}